<?php

declare(strict_types=1);

namespace App\Services;

use Hyperf\Di\Annotation\Inject;
use App\Exception\ApiException;
use App\Constants\ErrorCode;
use Hyperf\DbConnection\Db;
use App\Model\Goods;
use App\Model\AccountRecord;
use App\Model\GoodsCategory;
use App\Model\User;
use App\Model\UserOrder;

class GoodsService extends BaseService
{

    public function list(array $params)
    {
        $model = Goods::query()->select('id','category_id','title','image','price','num')->where('category_id', $params['category_id'])->where('status', 1)->where('deleted', 0);
        $list = $this->usePage($model)->toArray();

        return $list;
    }

    public function detail(array $params)
    {
        $user = auth_user();
        $goods = Goods::query()->with('goodsCategory')->select('id','goods_no','category_id','title','image','price','num','content')->where('id', $params['id'])->where('status', 1)->where('deleted', 0)->first();
        if(!$goods)
        {
            throw new ApiException(ErrorCode::WARNING, '商品不存在');
        }

        $goods['star_currency'] = $user['star_currency'];           //星币余额

        return $goods;
    }

    public function getCategory()
    {
        $goodsCategory = GoodsCategory::query()->select('id','name','remark')->where('status', 1)->where('deleted', 0)->get()->toArray();

        return $goodsCategory;
    }

    public function goodsExchange(array $params)
    {
        $user = auth_user();
        $user = User::query()->select('id','star_currency')->where('id', $user['id'])->first();      //获取用户实时星币余额(注意$user重新赋值)
        $goods = Goods::query()->select('id','goods_no','category_id','title','image','price','num','limit_num')->where('id', $params['id'])->where('status', 1)->where('deleted', 0)->first();
        if(!$goods)
        {
            throw new ApiException(ErrorCode::WARNING, '商品不存在');
        }

        if($params['num'] > $goods['num'])
        {
            throw new ApiException(ErrorCode::WARNING, '库存不足');
        }

        $amount = $goods['price'] * $params['num'];
        if($user['star_currency'] < $amount)
        {
            throw new ApiException(ErrorCode::WARNING, '星币不足');
        }

        if($goods['limit_num']>0 && $params['num']>$goods['limit_num'])
        {
            throw new ApiException(ErrorCode::WARNING, '每人兑换数量限制：'.$goods['limit_num']);
        }else{
            $buyNum = UserOrder::query()->where('user_id', $user['id'])->where('goods_id', $params['id'])->sum('num');
            if($goods['limit_num']>0 && $buyNum>=$goods['limit_num'])
            {
                throw new ApiException(ErrorCode::WARNING, '每人兑换数量限制：'.$goods['limit_num']);
            }
        }

        $userData['star_currency'] = $user['star_currency'] - $amount;

        $orderdata['user_id'] = $user['id'];
        $orderdata['goods_id'] = $params['id'];
        $orderdata['order_no'] = get_order_no();
        $orderdata['status'] = 1;        //待发货
        $orderdata['price'] = $goods['price']*$params['num'];
        $orderdata['num'] = $params['num'];
        
        $recordData['user_id'] = $user['id'];
        $recordData['category'] = 'star_currency';
        $recordData['type'] = 'expense';          //支出
        $recordData['detail'] = '商品兑换'.$amount;
        $recordData['star_currency'] = $amount;
        $recordData['star_currency_balance'] = $userData['star_currency'];

        $residueNum = $goods['num']-$params['num'];       //扣除库存

        Db::beginTransaction();
        try{
            Goods::query()->where('id', $params['id'])->update(['num' => $residueNum]);
            User::query()->where('id', $user['id'])->update($userData);
            UserOrder::query()->insert($orderdata);
            AccountRecord::query()->insert($recordData);

            Db::commit();
        } catch(\Throwable $e){
            Db::rollBack();
            throw new ApiException(ErrorCode::ERROR, $e->getMessage());
        }

        return [];
    }

}